<template>
  <n-drawer v-model:show="isDrawer" :width="width" :auto-focus="false" @after-leave="handleReset">
    <n-drawer-content :title="title" closable>
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="120"
      >

        <n-form-item label="门店名称" path="name">
          <n-input
            placeholder="请输入门店名称"
            v-model:value="formParams.name"
          />
        </n-form-item>

        <n-form-item label="所属区域">
          <n-select clearable placeholder="请选择省份" v-model:value="formParams.province" label-field="name" value-field="id" :options="provinceSelect" @update:value="privateChange"/>
          <n-select clearable placeholder="请选择市" v-model:value="formParams.city" label-field="fullname" value-field="id" :options="citySelect" @update:value="cityChange"/>
          <n-select clearable placeholder="请选择区" v-model:value="formParams.district" label-field="fullname" value-field="id" :options="districtSelect"/>
          <n-button type="primary" :loading="subLoading" @click="handleAgent">选择区域</n-button>
        </n-form-item>

        <n-form-item label="详细地址" path="full_address">
          <n-input placeholder="请输入详细地址" v-model:value="formParams.full_address" />
        </n-form-item>

        <n-form-item label="门店类型" path="store_type">
          <n-select clearable placeholder="请选择门店类型" v-model:value="formParams.store_type" label-field="name" value-field="id" :options="storeTypeAll" />
        </n-form-item>

        <n-form-item label="归属代理商">
          <n-input placeholder="请选择归属代理商" disabled v-model:value="formParams.charger_agents_name" />
          <n-button type="primary" @click="handleAgent1" ghost>
            选择代理商
          </n-button>
        </n-form-item>

        <n-form-item label="归属商户">
          <n-input placeholder="请选择归属商户" disabled v-model:value="formParams.charger_bussiness_name" />
          <n-button type="primary" @click="handleBusinesses" ghost>
            选择商户
          </n-button>
        </n-form-item>

        <n-form-item label="归属员工">
          <n-input placeholder="请选择归属员工" disabled v-model:value="formParams.charger_yuangong_name" />
          <n-button type="primary" @click="handleyuangong" ghost>
            选择员工
          </n-button>
        </n-form-item>
        
        <n-form-item label="门店电话" path="phone">
          <n-input placeholder="请输入门店电话" v-model:value="formParams.phone" />
        </n-form-item>

        <n-form-item label="联系人" path="lxname">
          <n-input placeholder="请输入联系人" v-model:value="formParams.lxname" />
        </n-form-item>

        <n-form-item label="营业时间">
          <n-input placeholder="请输入营业时间" v-model:value="formParams.yyshijian" />
          <!-- <n-time-picker format="HH:mm" @confirm="handleConfirm" /> -->
        </n-form-item>

        <n-form-item label="免押服务" path="depositstatus">
          <n-radio-group v-model:value="formParams.depositstatus" name="depositstatus">
            <n-space>
              <n-radio :key="0" :value="0">关闭</n-radio>
              <n-radio :key="1" :value="1">开启</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>

        <n-form-item label="充电宝权限" path="powerbank">
          <n-radio-group v-model:value="formParams.powerbank" name="powerbank">
            <n-space>
              <n-radio :key="0" :value="0">关闭</n-radio>
              <n-radio :key="1" :value="1">开启</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>

        <n-form-item label="充电线权限" path="chargingline">
          <n-radio-group v-model:value="formParams.chargingline" name="chargingline">
            <n-space>
              <n-radio :key="0" :value="0">关闭</n-radio>
              <n-radio :key="1" :value="1">开启</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>

        <n-form-item label="上传门店图片" path="sitepicture">
          <BasicUpload
              :action="`${uploadUrl1}/api/common/cosupdate`"
              :width="100"
              :height="100"
              name="file"
              @uploadChange="changeSitePicture"
              :max="2"
              :maxSize="10"
              v-model:value="sitepicture"
              helpText="单个文件不超过10MB，最多只能上传1个文件"
          />
        </n-form-item>
      </n-form>

      <template #footer>
        <n-space>
          <n-button @click="handleReset">重置</n-button>
          <n-button type="primary" :loading="subLoading" @click="formSubmit">提交</n-button>
        </n-space>
      </template>

      <n-modal v-model:show="showModal">
        <n-card
          style="width: 900px"
          title="地图选点"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
        <div style="display: flex;align-items: center;">
          <n-input
            placeholder="请输入地址"
            v-model:value="address"
          />
          <div style="width: 30px;margin-left: 5px;">
            <n-button strong secondary circle @click="searchHandle">
              <template #icon>
                <n-icon><Search size="40"/></n-icon>
              </template>
            </n-button>
          </div>
        </div>
        <div id="container" style="width: 800px;height: 400px;margin-top: 10px;">

        </div>
        <div style="display: flex;align-items: center;margin-top: 10px;">
          <div>当前选择地址:</div><div>{{ address }}</div><div> <n-button @click="selectAreaok">确认选择</n-button> </div>
        </div>
        <div>
          <n-table>
            <thead>
              <td>地区</td>
              <td>操作</td>
            </thead>
            <tbody v-for="(item,index) in areaList" :key="index">
              
              <td v-if="item.address==undefined">{{ item.title }}</td>
              <td v-else>{{ item.address }}</td>
              <td>
                <n-button strong secondary @click="selectArea(item)" type="info">
                  确认选择
                </n-button>
              </td>
            </tbody>
          </n-table>
        </div>
        </n-card>
      </n-modal>

      <n-modal v-model:show="showModal1">
        <n-card
          style="width: 600px"
          title="选择代理商"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
          <div style="display: flex;align-items: center;">
                <div style="width: 50px;">名称：</div>
                  <n-input
                    style="width: 50%;"
                    v-model:value="chargerParams.name"
                    clearable
                    placeholder="请输入名称"
                  />
                  <n-button style="margin-left: 10px" @click="chaSearchBut">搜索</n-button>
            </div>
          <n-table :bordered="false" :single-line="false">
            <thead>
            <tr>
              <th>代理商名称</th>
              <th>代理商账号</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item,index) in agentAll" :key="index">
              <td>{{item.nickname}}</td>
              <td>{{item.username}}</td>
              <td><n-button type="primary" @click="selectAgent(item)">选择</n-button></td>
            </tr>
          </tbody>
          </n-table>
          <n-pagination
              v-model:page="chargerParams.page"
              v-model:page-size="chargerParams.pageSize"
              :page-count="chargerParams.totalPage"
              show-size-picker
              :page-sizes="[10, 20, 30, 40]"
              :on-update-page="chargerChangePage"
              :on-update-page-size="chargerChangePagesize"
            />
        </n-card>
      </n-modal>

      <n-modal v-model:show="businessesModal">
        <n-card
          style="width: 600px"
          title="选择商户"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
          <div style="display: flex;align-items: center;">
                <div style="width: 50px;">名称：</div>
                  <n-input
                    style="width: 50%;"
                    v-model:value="stationParams.name"
                    clearable
                    placeholder="请输入名称"
                  />
                  <n-button style="margin-left: 10px" @click="staSearchBut">搜索</n-button>
            </div>
          <n-table :bordered="false" :single-line="false">
            <thead>
              <tr>
                <th>商户名称</th>
                <th>商户账号</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item,index) in businessesAll" :key="index">
                <td>{{item.nickname}}</td>
                <td>{{item.username}}</td>
                <td><n-button type="primary" @click="selectBusinesses(item)">选择</n-button></td>
              </tr>
            </tbody>
            
          </n-table>
          <n-pagination
              v-model:page="stationParams.page"
              v-model:page-size="stationParams.pageSize"
              :page-count="stationParams.totalPage"
              show-size-picker
              :page-sizes="[10, 20, 30, 40]"
              :on-update-page="stationChangePage"
              :on-update-page-size="stationChangePagesize"
            />
        </n-card>
      </n-modal>

      <n-modal v-model:show="yuangongModal">
        <n-card
          style="width: 600px"
          title="选择员工"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
          <div style="display: flex;align-items: center;">
            <div style="width: 50px;">名称：</div>
            <n-input
              style="width: 50%;"
              v-model:value="yuangongParams.name"
              clearable
              placeholder="请输入名称"
            />
            <n-button style="margin-left: 10px" @click="yuangongSearchBut">搜索</n-button>
          </div>
          <n-table :bordered="false" :single-line="false">
            <thead>
              <tr>
                <th>员工名称</th>
                <th>员工账号</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item,index) in yuangongAll" :key="index">
                <td>{{item.nickname}}</td>
                <td>{{item.username}}</td>
                <td><n-button type="primary" @click="selectyuangong(item)">选择</n-button></td>
              </tr>
            </tbody>
          </n-table>
          <n-pagination
              v-model:page="yuangongParams.page"
              v-model:page-size="yuangongParams.pageSize"
              :page-count="yuangongParams.totalPage"
              show-size-picker
              :page-sizes="[10, 20, 30, 40]"
              :on-update-page="yuangongChangePage"
              :on-update-page-size="yuangongChangePagesize"
            />
        </n-card>
      </n-modal>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup>
  import { ref, onMounted, computed, reactive, initCustomFormatter, inject } from 'vue';
  import { useMessage, FormRules } from 'naive-ui';
  import type { formParamsType } from './types';
  import { useDictionary } from '@/hooks/web/useDictionary';
  import { Search } from '@vicons/ionicons5';

  import { addUsur, editUsur, userInfo, getallagentList1, getallyuangongList1 } from '@/api/system/user';
  import { getMapList,getProvinceList,getAdcodeSearch,geocoderInfo,stationEdit,stationAdd,stationInfo } from '@/api/device/station';
  import { deptTreeList } from '@/api/auth/dept';
  import { postList } from '@/api/auth/post';
  import { SelectMixedOption } from 'naive-ui/es/select/src/interface';
  import { PicCenterOutlined } from '@vicons/antd';

  import { getStoreTypeList,bussinessCharger,yuangongCharger } from '@/api/device/charger';

  import { useGlobSetting } from '@/hooks/setting';
  const globSetting = useGlobSetting();
  const { uploadUrl } = globSetting;
  const uploadUrl1 = uploadUrl;
  const agentAll = ref([]);

  const rules: FormRules = {
    name: {
      required: true,
      message: '请输入门店名称',
      trigger: 'blur',
    },
    nickname: {
      required: true,
      message: '名称不能为空',
      trigger: 'blur',
    },
    full_address: {
      required: true,
      message: '请输入详细地址',
      trigger: 'blur',
    },
    phone: {
      required: true,
      message: '请输入门店电话',
      trigger: 'blur',
    },
    lxname: {
      required: true,
      message: '请输入联系人',
      trigger: 'blur',
    },
    tell: {
      required: true,
      message: '请输入联系电话',
      trigger: 'blur',
    },
    sitepicture:{
      required: true,
      message: '请上传门店图片',
      trigger: 'change',
    },
  };

  const emit = defineEmits(['change']);
  const { getDictTypeList } = useDictionary();
  const showModal1 = ref(false);
  const props = defineProps({
    title: {
      type: String,
      default: '添加门店',
    },
    width: {
      type: Number,
      default: 650,
    },
    roleList: {
      type: Array,
    },
  });

  const provinceSelect = ref([]);
  const citySelect = ref([]);
  const districtSelect = ref([]);
  const address = ref('');
  const sitepicture = ref([]);
  const businessesAll = ref([]);
  const yuangongAll = ref([]);
  const lvlv = ref(false);
  const defaultValueRef = () => ({
    id: null,
    name: '',
    province: '',
    city: '',
    district: '',
    full_address: '',
    store_type: null,
    phone: '',
    lxname: '',
    tell: '',
    yyshijian: '',
    beizhu: '',
    sitepicture: '',
    lat: '',
    lng: '',
    charger_agents_id: 0,
    charger_agents_name: '',
    charger_bussiness_id: 0,
    charger_bussiness_name: '',
    charger_yuangong_id: 0,
    charger_yuangong_name: '',
    province_text:'',
    city_text:'',
    district_text:'',
    depositstatus: 0,
    powerbank: 0,
    chargingline: 0,
  });

  const loc = ref({
    lat: 39.98210863924864,//维度
    lng: 116.31310899739151,//经度
    address: '',
    map:'',
  });

  const TMap = (window as any).TMap;
  const center = new TMap.LatLng(39.98210863924864, 116.31310899739151);
  var markerLayer = null;
  const init =()=>{
    var center = new TMap.LatLng(loc.value.lat, loc.value.lng);//设置中心点坐标
    //初始化地图
    loc.value.map = new TMap.Map("container", {
        center: center,//设置地图中心点坐标
        zoom: 17.2,   //设置地图缩放级别
        pitch: 43.5,  //设置俯仰角
        rotation: 45,    //设置地图旋转角度
    });
    loc.value.map.on('click',clickHandler); // 绑定点击地图获取地理位置的事件

  };

  function changeSitePicture(file){
    sitepicture.value = file;
  }

  function handleConfirm(value: number | null) {
    console.log(value)
  }

  function formSubmit() {
    formParams.value.sitepicture = sitepicture.value[0];
    formRef.value.validate((errors) => {
      if (!errors) {
        const msg = formParams.value.id ? '编辑成功' : '添加成功';
        //循环获取一下省份名称
        for(let i=0;i<provinceSelect.value.length;i++){
          if(provinceSelect.value[i].id == formParams.value.province){
            formParams.value.province_text = provinceSelect.value[i].fullname;
          }
        }
        //循环获取一下城市名称
        for(let i=0;i<citySelect.value.length;i++){//循环获取一下
          if(citySelect.value[i].id == formParams.value.city){
            formParams.value.city_text = citySelect.value[i].fullname;
          }
        }
        //循环获取一下区名称
        for(let i=0;i<districtSelect.value.length;i++){//循环获取一下
          if(districtSelect.value[i].id == formParams.value.district){
            formParams.value.district_text = districtSelect.value[i].fullname;
          }
        }

        if (formParams.value.id) {
          stationEdit(formParams.value).then((_)=>{
            message.success(msg);
            emit('change');
            handleReset();
            closeDrawer();
          });
        } else {
          formParams.value.lat = loc.value.lat;
          formParams.value.lng = loc.value.lng;
          stationAdd(formParams.value).then((_)=>{
            message.success(msg);
            emit('change');
            handleReset();
            closeDrawer();
          });
        }
      } else {
        message.error('请填写完整信息');
      }
    });
  }

  function getInfo() {
    stationInfo({ id: formParams.value.id }).then((res) => {
      const params = {
        id: formParams.value.id,
        name: res.name,
        province: res.province,
        city: res.city,
        district: res.district,
        full_address: res.full_address,
        station_type: res.station_type,
        depositstatus: res.depositstatus,
        powerbank: res.powerbank,
        chargingline: res.chargingline,
        phone: res.phone,
        lxname: res.lxname,
        tell: res.tell,
        yyshijian: res.yyshijian,
        beizhu: res.beizhu,
        store_type: parseInt(res.store_type),
        lat: res.lat,
        lng: res.lng,
        charger_agents_id: res.charger_agents_id,
        charger_agents_name: res.charger_agents_name,
        charger_bussiness_id: res.charger_bussiness_id,
        charger_bussiness_name: res.charger_bussiness_name,
        charger_yuangong_id: res.charger_yuangong_id,
        charger_yuangong_name: res.charger_yuangong_name,
        province_text:res.province_text,
        city_text:res.city_text,
        district_text:res.district_text
      };
      loc.value.lat = params.lat;
      loc.value.lng = params.lng;
      sitepicture.value[0] = res.sitepicture;

      formParams.value = Object.assign(formParams.value, params);

      //获取所有的市级列表
      privateChange(res.province);

      //获取所有的区级列表
      cityChange(res.city);

      isDrawer.value = true;
    });
  }

  function selectAreaok(){
    showModal.value = false;
    formParams.value.full_address = address.value;
  }

  function selectArea(item){
    if(item.address==undefined){
      address.value = item.title;
    }else{
      address.value = item.address;
    }
    formParams.value.full_address = item.address;
    showModal.value = false;
  }

  //移除marker事件
  function removeMarker(){
    if(markerLayer!=null){
      markerLayer.setMap(null);
      markerLayer = null;
    }
  }

  function createMarker(latLng){
    markerLayer = new TMap.MultiMarker({
      id: 'marker',
      map: loc.value.map,
      styles:{
        marker: new TMap.MarkerStyle({
          width: 20, // 样式宽
          height: 30, // 样式高
          anchor: { x: 10, y: 30 }, // 描点位置
        }),
      },
      geometries: [
        // 点标记数据数组
        {
          //标记位置
          position:latLng,
          id: 'marker',
        }
      ]
    });
  }
        
   // 点击获取经纬度
   const clickHandler = (evt:any) => {
      loc.value.lat = evt.latLng.getLat().toFixed(6);//维度
      loc.value.lng = evt.latLng.getLng().toFixed(6);//经度
      removeMarker();
      createMarker(evt.latLng);
      //根据点击坐标获取地址

      geocoderInfo({ 'lat':loc.value.lat,'lng':loc.value.lng }).then((res) => {

        address.value = res.formatted_addresses.standard_address;
        var adcode = res.ad_info.adcode;
        
        formParams.value.province = adcode.substring(0,2)+'0000';

        //查询一下市列表
        privateChange(formParams.value.province);

        //判断一下是不是直辖市
        if(formParams.value.province=='110000'||formParams.value.province=='120000'||formParams.value.province=='310000'||formParams.value.province=='500000'){
          formParams.value.city = adcode;
          formParams.value.district = adcode;
        }else{

          formParams.value.city = adcode.substring(0,4)+'00';
          // 查询一下区列表
          cityChange(formParams.value.city);
          formParams.value.district = adcode;
        }
      });
    };

  const showModal = ref(false);
  const divided2 = ref(true);
  const dividedStatus = ref(true);
  const message = useMessage();
  const formRef: any = ref(null);
  const isDrawer = ref(false);
  const subLoading = ref(false);
  const cities = ref(null);
  const areaList = ref([]);
  const storeTypeAll = ref([]);
  const businessesModal = ref(false);
  const yuangongModal = ref(false);

  const formParams = ref<formParamsType>(defaultValueRef());

  const getRoleList = computed(() => {
    return props.roleList as SelectMixedOption[];
  });

  const reloadMap = () => {
    (document.getElementById('container') as any).innerHTML = '';
    loc.value.map = '';
    var center = new TMap.LatLng(loc.value.lat, loc.value.lng);//设置中心点坐标
    //初始化地图
    loc.value.map = new TMap.Map("container", {
        center: center,//设置地图中心点坐标
        zoom: 17.2,   //设置地图缩放级别
        pitch: 43.5,  //设置俯仰角
        rotation: 45,    //设置地图旋转角度
    });
    loc.value.map.on('click',clickHandler); // 绑定点击地图获取地理位置的事件
  }

  function searchHandle(){
    //搜索
    getMapList({ address:address.value }).then((res) => {

      loc.value.lat = res.data[0].location.lat;;//维度
      loc.value.lng = res.data[0].location.lng;//经度
      if(res.data[0].address==undefined){
        address.value = res.data[0].title;
      }else{
        address.value = res.data[0].address;
      }
      areaList.value = res.data;
      reloadMap();

      removeMarker();
      createMarker(new TMap.LatLng(loc.value.lat,loc.value.lng));
    })
  }

  const stationParams = ref({
    name:'',
    page:1,
    pageSize:10,
    totalPage:1,
    charger_agents_id:''
  });

  const chargerParams = ref({
    name:'',
    page:1,
    pageSize:10,
    totalPage:1,
  });

  const yuangongParams = ref({
    name:'',
    page:1,
    pageSize:10,
    totalPage:1,
    charger_agents_id:''
  });

  //代理商分页
  async function chargerChangePage(e){
    //改变一下页数
    chargerParams.value.page = e;
    //重新请求一下接口
    var agentAll1 = await getallagentList1(chargerParams.value);
    chargerParams.value.totalPage = agentAll1.totalPage;
    agentAll.value = agentAll1.list;
  }
  
  async function chargerChangePagesize(e){
    //改变条数
    chargerParams.value.pageSize = e;
    var agentAll1 = await getallagentList1(chargerParams.value);   
    chargerParams.value.totalPage = agentAll1.totalPage;
    agentAll.value = agentAll1.list;
  }

  //代理商搜索
  async function chaSearchBut(){
    var agentAll1 = await getallagentList1(chargerParams.value);
    chargerParams.value.totalPage = agentAll1.totalPage;
    agentAll.value = agentAll1.list;
  }


  //商家搜索
  async function staSearchBut(){
    var result = await bussinessCharger(stationParams.value);
    stationParams.value.totalPage = result.totalPage;
    businessesAll.value = result.list;
  }
  //商家分页
  async function stationChangePage(e){
    //改变一下页数
    stationParams.value.page = e;
    //重新请求一下接口
    var result = await bussinessCharger(stationParams.value);
    stationParams.value.totalPage = result.totalPage;
    businessesAll.value = result.list;
  }
  async function stationChangePagesize(e){
    //改变条数
    stationParams.value.pageSize = e;

    var result = await bussinessCharger(stationParams.value);

    stationParams.value.totalPage = result.totalPage;
    businessesAll.value = result.list;
  }

  //员工搜索
  async function yuangongSearchBut(){
    var result = await yuangongCharger(yuangongParams.value);
    yuangongParams.value.totalPage = result.totalPage;
    yuangongAll.value = result.list;
  }
  //员工分页
  async function yuangongChangePage(e){
    //改变一下页数
    yuangongParams.value.page = e;
    //重新请求一下接口
    var result = await yuangongCharger(yuangongParams.value);
    yuangongParams.value.totalPage = result.totalPage;
    yuangongAll.value = result.list;
  }
  async function yuangongChangePagesize(e){
    //改变条数
    yuangongParams.value.pageSize = e;

    var result = await yuangongCharger(yuangongParams.value);

    yuangongParams.value.totalPage = result.totalPage;
    yuangongAll.value = result.list;
  }

  //选择代理商
  async function selectAgent(item){
    //商户
    formParams.value.charger_bussiness_id = 0;
    formParams.value.charger_bussiness_name = '';

    //员工
    formParams.value.charger_yuangong_id = 0;
    formParams.value.charger_yuangong_name = '';

    //代理商
    formParams.value.charger_agents_id = item.id;
    formParams.value.charger_agents_name = item.username;

    showModal1.value = false;
    //查询一下属于这个代理商的商户
    stationParams.value.charger_agents_id = item.id;
    var result = await bussinessCharger(stationParams.value);
    stationParams.value.totalPage = result.totalPage;
    businessesAll.value = result.list;

    //查询一下属于这个代理商的员工
    yuangongParams.value.charger_agents_id = item.id;
    var result1 = await yuangongCharger(yuangongParams.value);
    yuangongParams.value.totalPage = result1.totalPage;
    yuangongAll.value = result1.list;
  }

  //选择商户
  function selectBusinesses(item){
    //商户id
    formParams.value.charger_bussiness_id = item.id;
    //商户名称
    formParams.value.charger_bussiness_name = item.username;
    
    businessesModal.value = false;
  }

  //选择员工
  function selectyuangong(item){
    //员工id
    formParams.value.charger_yuangong_id = item.id;
    //员工名称
    formParams.value.charger_yuangong_name = item.username;
    
    yuangongModal.value = false;
  }

  function handleBusinesses(){
    if(formParams.value.charger_agents_name == ''){
      message.error('请选择代理商信息');
    }else{
      businessesModal.value = true;
    }
  }

  async function handleyuangong(){
    yuangongParams.value.charger_agents_id = formParams.value.charger_agents_id;

    var result1 = await yuangongCharger(yuangongParams.value);
    yuangongParams.value.totalPage = result1.totalPage;
    yuangongAll.value = result1.list;

    yuangongModal.value = true;
  }

  function handleAgent1(){
    showModal1.value = true;
  }

  function handleAgent(){
    showModal.value = true;
    setTimeout(async () => {
      if(formParams.value.district != ''){
        var result = await getAdcodeSearch({ adcode:formParams.value.district });
        address.value = result.address;
        searchHandle();
      }else{
        init();
      }
    }, 200);
  }

  async function openDrawer(id?) {
    if (id) {
      formParams.value.id = id;
      getInfo();
      return;
    }else{
      formParams.value = defaultValueRef();

      stationParams.value.name = '';
      stationParams.value.page = 1;
      stationParams.value.pageSize = 10;
      stationParams.value.totalPage = 1;
      stationParams.value.charger_agents_id = '';

      yuangongParams.value.name = '';
      yuangongParams.value.page = 1;
      yuangongParams.value.pageSize = 10;
      yuangongParams.value.totalPage = 1;
      yuangongParams.value.charger_agents_id = '';

      chargerParams.value.name = '';
      chargerParams.value.page = 1;
      chargerParams.value.pageSize = 10;
      chargerParams.value.totalPage = 1;
    }
    isDrawer.value = true;
  }

  // function dividedChange(e){
  //   if(e==1&&dividedStatus.value){
  //     divided2.value = true;
  //   }else{
  //     divided2.value = false;
  //   }
  // }

  function closeDrawer() {
    isDrawer.value = false;
  }

  function handleReset() {
    formRef.value.restoreValidation();
    formParams.value = Object.assign(formParams.value, defaultValueRef());
  }

  function addCodeList(){
    getProvinceList({ id: formParams.value.id }).then((res) => {
      provinceSelect.value = res;
    });
  }

  //获取所有的市级列表
  function privateChange(e){
    getProvinceList({ id: formParams.value.id, adcode:e }).then((res) => {
      citySelect.value = res;
      if(e == '110000'||e == '120000'||e == '310000'||e == '500000' ){
        districtSelect.value = citySelect.value;
      }
    });
  }

  //获取所有的区级列表
  function cityChange(e){
    if(formParams.value.province == '110000'||formParams.value.province == '120000'||formParams.value.province == '310000'||formParams.value.province == '500000'){
        districtSelect.value = citySelect.value;
    }else{
      getProvinceList({ id: formParams.value.id, adcode:e }).then((res) => {
        if(res==null){
          districtSelect.value = citySelect.value
        }else{
          districtSelect.value = res;
        }
      });
    }
  }

  onMounted(async () => {
    addCodeList();
    var agentAll1 = await getallagentList1(chargerParams.value);
    chargerParams.value.totalPage = agentAll1.totalPage;
    agentAll.value = agentAll1.list;

    //所有员工
    var yuangongAll1 = await getallyuangongList1(yuangongParams.value);
    yuangongParams.value.totalPage = yuangongAll1.totalPage;
    yuangongAll.value = yuangongAll1.list;

    //查询所有的设备类型
    var storeType = await getStoreTypeList({});
    storeTypeAll.value = storeType;
  });

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>
